package com.pengcheng.hnweb.listener;

import com.pengcheng.hnweb.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class RedisKeyExpiredListener implements MessageListener {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private FileUtil fileUtil;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("key过期:"+expiredKey);
        if(expiredKey.startsWith("check_sn:"))
        {
            String channel_id=expiredKey.split(":")[1];
            String sql="select * from hnww_device where channel_id=?";
            Object[] ps={channel_id};
            List<Map<String,Object>> list_device=jdbcTemplate.queryForList(sql,ps);
            if(list_device==null||list_device.size()==0)
            {
                //没有收到sn的值，提出
                Map<String,Object> map=new HashMap<>();
                map.put("type",1);
                map.put("channel_id",channel_id);
                rabbitTemplate.convertAndSend("hnww.kickout",map);
                fileUtil.add_msg(channel_id,"超时退出");
                log.info("提出："+channel_id);
            }
        }
    }
}
